//
//  YKCarouselScrollView.swift
//  YKCarouselScrollView
//
//  Created by YK on 16/2/15.
//  Copyright © 2016年 YK. All rights reserved.
//

import UIKit

protocol YKCarouselScrollViewDelegate: NSObjectProtocol{
    func tapAtIndex(index:Int);
}


class YKCarouselScrollView: UIView,UIScrollViewDelegate {
    
    var carouselScrollView:UIScrollView!
    var currentPage = 0
    var pictures:[String]?
    var isNetworkPic = true
    
    private var timer:NSTimer!
    var timerDuration:Double = 3.0
    
    var pageControl:UIPageControl!
    var currentPageTintColor: UIColor?
    var pageIndicatorTintColor: UIColor?
    
    weak var delegate: YKCarouselScrollViewDelegate?
    
    override  init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        self.initScrollView()
        self.initSubView()
    }
    
    /**
     加载ScrollView
    */
    func initScrollView() {
        if(carouselScrollView == nil){
            carouselScrollView = UIScrollView(frame:CGRectMake(0, 0, frame.size.width, frame.size.height))
            carouselScrollView.delegate = self
            carouselScrollView.pagingEnabled = true
            carouselScrollView.bounces = false
            carouselScrollView.showsHorizontalScrollIndicator = false
            self.addSubview(carouselScrollView)
            
            let tapGes = UITapGestureRecognizer(target: self, action: "tapAction")
            carouselScrollView.addGestureRecognizer(tapGes)
        }
    }
    
    /**
     点击触发
     */
    func tapAction() {
        self.delegate?.tapAtIndex(self.currentPage)
    }
    
    /**
     加载ImageView&&pageControl
     */
    func initSubView() {
        for  view in self.carouselScrollView.subviews {
            view.removeFromSuperview()
        }
        self.addPageControl()
        if(pictures!.count == 1){
            let imageView = UIImageView(frame: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height))
            self.addSubview(imageView)
            self.loadPic(imageView, picStr: self.pictures!.first!)
            carouselScrollView.contentSize = CGSizeMake(CGFloat(pictures!.count)*self.frame.size.width, self.frame.size.height)
        }else if(pictures!.count == 0){
            carouselScrollView.contentSize = CGSizeMake(CGFloat(pictures!.count)*self.frame.size.width, self.frame.size.height)
            return
        }else{
           self.addImageView()
           self.fixPageNumber()
           self.startTimer()
        }
    }
    
    /**
     加载pageControl
     */
    func addPageControl() {
        self.pageControl = UIPageControl(frame: CGRectMake(0, self.frame.size.height-20, self.frame.size.width, 20))
        self.pageControl.numberOfPages = self.pictures!.count
        self.pageControl.currentPage = self.currentPage
        if(self.currentPageTintColor != nil){
            self.pageControl.currentPageIndicatorTintColor = self.currentPageTintColor
        }
        if(self.pageIndicatorTintColor != nil){
            self.pageControl.pageIndicatorTintColor = self.pageIndicatorTintColor
        }
        self.addSubview(pageControl)
    }
    
    /**
     加载ImageView
     */
    func addImageView() {
           carouselScrollView.contentSize = CGSizeMake(CGFloat(3)*self.frame.size.width, self.frame.size.height)
        for(var i=0;i<3;i++){
            let imageView = UIImageView(frame: CGRectMake(CGFloat(i)*self.frame.size.width, 0, self.frame.size.width, self.frame.size.height))
            imageView.tag = 1000 + i;
            imageView.backgroundColor = UIColor.yellowColor()
            carouselScrollView.addSubview(imageView)
        }
    }
    
    /**
     加载图片
     */
    func loadPic(imageView:UIImageView, picStr:String) {
        if(isNetworkPic){
            imageView.sd_setImageWithURL(NSURL(string: picStr), placeholderImage: UIImage(named: ""))
        }else{
            imageView.image = UIImage(named: picStr)
        }
    }
    
    
//MARK:FixCurrentPage

    /**
     FixCurrentPage
     */
    func fixCurrentPage(page:CGFloat) {
        if(page == 0){
            self.currentPage--;
            self.fixPageNumber()
        }else if(page == 2){
            currentPage++;
            self.fixPageNumber()
        }
    }
    
    func fixPageNumber() {
        currentPage = self.checkPage(self.currentPage)
        let left = self.checkPage(self.currentPage-1)
        let right = self.checkPage(self.currentPage+1)
        self.pageControl.currentPage = self.currentPage
        self.refreshNewPic([left,self.currentPage,right])
    }
    
    /**
     检查越界
     */
    func checkPage(page:Int) -> Int {
        if(page == -1){
            return self.pictures!.count-1
        }else if(page == self.pictures!.count){
            return 0
        }else{
            return page;
        }
    }
    
    /**
     更新图片
     */
    func refreshNewPic(indexArray:[Int]) {
        carouselScrollView.setContentOffset(CGPointMake(carouselScrollView.frame.size.width, 0), animated: false)
        for(var i=0;i<3;i++){
            let imageView = carouselScrollView.viewWithTag(1000+i) as! UIImageView
            self.loadPic(imageView, picStr: self.pictures![indexArray[i]])
        }
    }
    
//MARK:  NStimer
    func startTimer() {
        if(self.timer == nil){
            self.timer = NSTimer.scheduledTimerWithTimeInterval(timerDuration, target: self, selector: "timerAction", userInfo: nil, repeats: true)
        }
    }
    
    func timerAction() {
        self.carouselScrollView.setContentOffset(CGPointMake(self.carouselScrollView.contentOffset.x + self.carouselScrollView.frame.size.width, self.carouselScrollView.contentOffset.y), animated: true)
    }
    
    func stopTimer() {
        if(self.timer != nil){
            self.timer.invalidate()
            self.timer = nil
        }
    }
    
    
//MARK:  scrollViewDelegate
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let page = scrollView.contentOffset.x / scrollView.frame.size.width
        self.fixCurrentPage(page)
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.stopTimer()
    }
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if(decelerate == false){
            self.startTimer()
        }
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        self.startTimer()
    }
    
}
